package com.chenjt.netty.six_gPRC.streamRequest;

import com.chenjt.netty.six_gPRC.generateCode.StudentRequest;
import com.chenjt.netty.six_gPRC.generateCode.StudentResponse;
import com.chenjt.netty.six_gPRC.generateCode.StudentResponseList;
import com.chenjt.netty.six_gPRC.generateCode.StudentServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.Iterator;

/**
 * gRPC客户端
 *
 * 参考D:\programmer\studyWorkspace\netty\doc\grpc-java\examples\src\main\java\io\grpc\examples\helloworld\HelloWorldClient.java
 * @author chenjt
 * @date 2024/8/16 10:36
 */
public class GrpcClient {

    public static void main(String[] args) {

        // 只要客户端是以流式的形式向服务器端发送一个请求，这种请求一定都是异步的
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 8899)
//                .usePlaintext(true)
                .usePlaintext()
                .build();
        // 异步
        StudentServiceGrpc.StudentServiceStub stub = StudentServiceGrpc.newStub(managedChannel);


        StreamObserver<StudentResponseList> studentResponseListStreamObserver = new StreamObserver<StudentResponseList>() {

            @Override
            public void onNext(StudentResponseList studentResponseList) {
                studentResponseList.getStudentResponseList().forEach(studentResponse -> {
                    System.out.println(studentResponse.getName());
                    System.out.println(studentResponse.getAge());
                    System.out.println(studentResponse.getCity());
                    System.out.println("******");
                });
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }

            @Override
            public void onCompleted() {
                System.out.println("completed!");
            }
        };

        // 这里的调用是异步的，执行完之后不等结果返回，就继续执行下面的代码了
        StreamObserver<StudentRequest> studentRequestStreamObserver = stub.getStudentsWrapperByAges(studentResponseListStreamObserver);

        // 传多个数据
        studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(20).build());
        studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(30).build());
        studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(40).build());
        studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(50).build());

        studentRequestStreamObserver.onCompleted();

        // 睡一下等待异步调用返回数据
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }



}
